/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hiddendanger.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.audit.mapper.AuditMapper;
import com.koron.common.bean.DeptBean;
import com.koron.common.bean.SecretBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.stub.Port;
import com.koron.common.web.Util;
import com.koron.hazardsource.domain.IndicationItems;
import com.koron.hazardsource.mapper.IndicationItemsMapper;
import com.koron.hazardsource.service.api.IndicationItemsService;
import com.koron.hazardsource.util.Immutable;
import com.koron.hiddendanger.bean.CheckRecordAtrrBean;
import com.koron.hiddendanger.bean.CheckRecordDetail;
import com.koron.hiddendanger.bean.CheckRecordReport;
import com.koron.hiddendanger.domain.*;
import com.koron.hiddendanger.mapper.*;
import com.koron.hiddendanger.service.api.CheckRecordService;
import com.koron.hiddendanger.service.api.ChecklistEntryReferenceService;
import com.koron.hiddendanger.service.api.HiddenDangerDiscoveryService;
import com.koron.hiddendanger.uitls.BusinessCode;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.mapper.CorpManagementMapper;
import com.koron.risk.service.api.GridNodeService;
import com.koron.risk.util.GridHelpUtils;
import com.koron.safetytask.domain.JobsTasks;
import com.koron.safetytask.mapper.JobsTasksMapper;
import com.koron.system.domain.DictData;
import com.koron.system.domain.Message;
import com.koron.system.mapper.DictDataMapper;
import com.koron.system.mapper.MessageMapper;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CheckRecordServiceImpl implements CheckRecordService, AfterApprovalService, InitializingBean {

    @Value("${app.appid}")
    private String appid;

    @Value("${app.secret}")
    private String secret;

    @Value("${risk_danger_setCode}")
    private String riskDangerSetCode;

    @Value("${danger_work_flow}")
    private String hiddenDangerWorkFlow;

    private final static  Logger logger = LoggerFactory.getLogger(CheckRecordServiceImpl.class);

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private HiddenDangerDiscoveryService dangerDiscoveryService;

    @Autowired
    private ChecklistEntryReferenceService referenceService;

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private Util util;

    @Override
    public MessageBean<String> save(StaffBean user, CheckRecord checkRecord, MultipartFile[] inspectorsSignFile, String keepInspectorsSignFile, String delInspectorsSignFile, MultipartFile[] signFile, String keepSignFile, String delSignFile) {
        MessageBean<String> msg = new MessageBean<>();
        List<String> addFile = new ArrayList<>();
        List<String> keepInspectorsSignList = new ArrayList<>();
        List<String> keepSignList = new ArrayList<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(checkRecord.getName())) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_NAME.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_NAME.getDescription());
                return msg;
            }
//            if (null == checkRecord.getRectificationPeriod()) {
//                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_NAME.getCode());
//                msg.setDescription("整改时限不能为空");
//                return msg;
//            }
//            if (StringUtils.isEmpty(checkRecord.getCorpCode())) {
//                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CROPCODE.getCode());
//                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CROPCODE.getDescription());
//                return msg;
//            }
//            if (StringUtils.isEmpty(checkRecord.getSubmitCode())) {
//                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_SUBMITCODE.getCode());
//                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_SUBMITCODE.getDescription());
//                return msg;
//            }
//            if (StringUtils.isEmpty(checkRecord.getManager())) {
//                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_MANAGER.getCode());
//                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_MANAGER.getDescription());
//                return msg;
//            }
            List<DictData> dataList = new ArrayList<>();
            List<IndicationItems> itemsList = new ArrayList<>();
            if (StringUtils.isNotEmpty(checkRecord.getCheckTheme())) {
                DictData data = factory.getMapper(DictDataMapper.class).queryOne(checkRecord.getCheckLevel());
                if (null != data) {
                    data.setReferenceCount(data.getReferenceCount() + 1);
                    dataList.add(data);
                }
            }
            if (StringUtils.isNotEmpty(checkRecord.getCheckLevel())) {
                IndicationItems items = factory.getMapper(IndicationItemsMapper.class).queryOne(checkRecord.getCheckLevel());
                if (null != items) {
                    items.setReferenceCount(items.getReferenceCount() + 1);
                    itemsList.add(items);
                }
            }
            if (StringUtils.isNotEmpty(keepInspectorsSignFile)) {
                List<String> list = Arrays.asList(keepInspectorsSignFile.split("[,，]"));
                keepInspectorsSignList.addAll(list);
            }
            if (StringUtils.isNotEmpty(keepSignFile)) {
                List<String> list = Arrays.asList(keepSignFile.split("[,，]"));
                keepSignList.addAll(list);
            }
            if (null != inspectorsSignFile && inspectorsSignFile.length > 0) {
                for (MultipartFile file : inspectorsSignFile) {
                    String url = clientWrapper.uploadFile(file);
                    addFile.add(url + "#" + file.getOriginalFilename());
                    keepInspectorsSignList.add(url + "#" + file.getOriginalFilename());
                }
            }
            if (null != signFile && signFile.length > 0) {
                for (MultipartFile file : signFile) {
                    String url = clientWrapper.uploadFile(file);
                    addFile.add(url + "#" + file.getOriginalFilename());
                    keepSignList.add(url + "#" + file.getOriginalFilename());
                }
            }
            checkRecord.setInspectorsSign((null == keepInspectorsSignList || keepInspectorsSignList.size() <= 0) ? null : new Gson().toJson(keepInspectorsSignList));
            checkRecord.setInspectedUnitLeadSign((null == keepSignList || keepSignList.size() <= 0) ? null : new Gson().toJson(keepSignList));
            Integer value = 0;
            if (StringUtils.isEmpty(checkRecord.getId())) {
                //新增
                checkRecord.setAddTime(checkRecord.getUpdateTime());
                checkRecord.setAddUser(checkRecord.getUpdateUser());
                checkRecord.setId(DefaultIdGenerator.getInstance().generateLongId());
                checkRecord.setCode(generateCaode(factory, checkRecord.getCorpCode()));
                checkRecord.setSubmit(0);
                value = factory.getMapper(CheckRecordMapper.class).insert(checkRecord);
            } else {
                //修改
                CheckRecord entity = factory.getMapper(CheckRecordMapper.class).queryOne(checkRecord.getId());
                if (null == entity) {
                    msg.setCode(BusinessCode.CHECKRECORD_NOT_EXISIT.getCode());
                    msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXISIT.getDescription());
                    return msg;
                }
                if (null != user && entity.getWorkflowEditState() != 1) {
                    // 判断当前登录用户是不是检查记录提交人或审批人
                    if (entity.getSubmitCode().equals(user.getCode()) || entity.getIdentifier().split("_")[0].equals(user.getCode())) {
                        entity.setWorkflowEditState(1);
                    } else if (StringUtils.isNotEmpty(entity.getNextParticipantCode()) && user.getUserid().equals(entity.getNextParticipantCode())) {
                        entity.setWorkflowEditState(1);
                    }
                }
                if (entity.getSubmit() == 1 && entity.getWorkflowEditState() != 1) {
                    msg.setCode(BusinessCode.CHECKRECORD_IS_COMMITED.getCode());
                    msg.setDescription(BusinessCode.CHECKRECORD_IS_COMMITED.getDescription());
                    return msg;
                }
                value = factory.getMapper(CheckRecordMapper.class).update(checkRecord);
            }
            if (value > 0) {
                if (!itemsList.isEmpty()) {
                    factory.getMapper(IndicationItemsMapper.class).batchUpdate(itemsList);
                }
                if (!dataList.isEmpty()) {
                    factory.getMapper(DictDataMapper.class).batchUpdate(dataList);
                }
                if (StringUtils.isNotEmpty(delInspectorsSignFile)) {
                    String[] delUrl = delInspectorsSignFile.split("[,，]");
                    for (String url : delUrl) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
                if (StringUtils.isNotEmpty(delSignFile)) {
                    String[] delUrl = delSignFile.split("[,，]");
                    for (String url : delUrl) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("保存成功");
                msg.setData(checkRecord.getId());
                factory.close();
                return msg;
            } else {
                if (null != addFile && addFile.size() > 0) {
                    for (String url : addFile) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("保存失败");
                factory.close(false);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> commit(StaffBean user, String id, String jobsTasksId) {
        MessageBean<Integer> msg = new MessageBean<>();
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            CheckRecord entity = factory.getMapper(CheckRecordMapper.class).queryOne(id);
            if (null == entity) {
                msg.setCode(BusinessCode.CHECKRECORD_NOT_EXISIT.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXISIT.getDescription());
                return msg;
            }
            if (entity.getSubmit() == 1) {
                msg.setCode(BusinessCode.CHECKRECORD_IS_COMMITED.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_IS_COMMITED.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(entity.getName())) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_NAME.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_NAME.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(entity.getCorpCode())) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CROPCODE.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CROPCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(entity.getSubmitCode())) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_SUBMITCODE.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_SUBMITCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(entity.getManager())) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_MANAGER.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_MANAGER.getDescription());
                return msg;
            }
            CheckRecordMapper recordMapper = factory.getMapper(CheckRecordMapper.class);
//            AuditMapper auditMapper = factory.getMapper(AuditMapper.class);
            entity.setSubmit(1);
            entity.setUpdateUser(user == null ? null : user.getName());
            entity.setUpdateTime(new Date());
            entity.setSubmitTime(entity.getUpdateTime());
            entity.setSubmitCode(user.getCode());
            recordMapper.update(entity);
//            List<HiddenDangerDiscovery> dangerDiscoveries = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(entity.getId(), null, null);
//            if (null != dangerDiscoveries && dangerDiscoveries.size() > 0) {
//                factory.getMapper(HiddenDangerMapper.class).batchUpdateDanger(dangerDiscoveries);
//            }
            if (StringUtils.isNotEmpty(jobsTasksId)) {
                //更新任务
                JobsTasks jobsTasks = factory.getMapper(JobsTasksMapper.class).queryById(jobsTasksId);
                if (null != jobsTasks) {
                    jobsTasks.setBusinessId(id);
                    jobsTasks.setState(3);
                    jobsTasks.setCompletedTime(new Date());
                    factory.getMapper(JobsTasksMapper.class).completed(jobsTasks);
                }
            }
            //构造Audit
            Audit audit = new Audit();
            audit.setAddUser(user == null ? null : user.getName());
            audit.setAddTime(entity.getSubmitTime());
            audit.setUpdateUser(user == null ? null : user.getName());
            audit.setUpdateTime(entity.getSubmitTime());
            audit.setFlowType(1);
            audit.setFlowName(Immutable.CHECKRECORD_RESULT_CONFIRM);
            audit.setOperation(1);
            audit.setTarget(CheckRecordServiceImpl.class.getName());
            audit.setTitle(entity.getName());
            audit.setCorpCode(entity.getCorpCode());
            audit.setBusinessIds(entity.getId());
            audit.setInitiatorCode(entity.getSubmitCode().split("_")[0]);
            audit.setDescription(StringUtils.isNotEmpty(entity.getDescription()) ? entity.getDescription() : "检查记录流程");
            audit.setState(1);
//            audit.setTemplateKey(checkRecordTemplate);
            audit.setTemplateKey("check_record_confirm");
            audit.setInitiatorAccount(user.getUserid());
            audit.setSetCode(riskDangerSetCode);
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            Map<String, Object> businessMap = new HashMap<>();
//            businessMap.put("manager", entity.getManager().split("_")[1]);
            businessMap.put("identifier", entity.getIdentifier().split("_")[1]);
//            if (StringUtils.isNotEmpty(entity.getInnerWorkers())) {
//                List<String> innerWorkers = JSONObject.parseArray(entity.getInnerWorkers(), String.class);
//                StringBuilder codes = new StringBuilder();
//                for (String code : innerWorkers) {
//                    codes.append(code.split("_")[1]).append(",");
//                }
//                businessMap.put("innerWorkers", codes.toString().substring(0, codes.lastIndexOf(",")));
//            }
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("提交失败");
                return msg;
            } else {
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("提交成功");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            factory.close();
        }
    }

    @Override
    public MessageBean<Integer> batchDelete(StaffBean user, List<String> idList) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (null == idList || idList.size() <= 0) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getDescription());
                factory.close();
                return msg;
            }
            Boolean authority = util.getAuthority(user);
            List<String> authorityList = new ArrayList<>();
            List<String> delIdList = new ArrayList<>();
            for (String id : idList) {
                CheckRecord record = factory.getMapper(CheckRecordMapper.class).queryOne(id);
                if (record != null && record.getSubmit() == 0) {
                    delIdList.add(id);
                } else if (authority) {
                    delIdList.add(id);
                    authorityList.add(id);
                }
            }
            if (null == delIdList || delIdList.size() <= 0) {
                msg.setCode(BusinessCode.CHECKRECORD_IS_COMMITED.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_IS_COMMITED.getDescription());
                factory.close();
                return msg;
            }
            Integer value = factory.getMapper(CheckRecordMapper.class).deleteBatch(delIdList);
            if (value > 0) {
                // 删除其他相关数据
                if (null != authorityList && authorityList.size() > 0) {
                    deleteAuthority(authorityList);
                }
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("删除成功");
                msg.setData(value);
                factory.close();
                return msg;
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
                msg.setData(value);
                factory.close(false);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 删除检查记录相关数据
     *
     * @param idList
     */
    private void deleteAuthority(List<String> idList) {
        try (SessionFactory factory = new SessionFactory()) {
            ChecklistEntryReferenceMapper checklistEntryReferenceMapper = factory.getMapper(ChecklistEntryReferenceMapper.class);
            HiddenDangerMapper hiddenDangerMapper = factory.getMapper(HiddenDangerMapper.class);
            HiddenDangerRectificationMapper rectificationMapper = factory.getMapper(HiddenDangerRectificationMapper.class);
            AuditMapper auditMapper = factory.getMapper(AuditMapper.class);
            if (null != idList && idList.size() > 0) {
                for (String id : idList) {
                    // 获取是否有隐患
                    List<HiddenDangerDiscovery> discoveryList = hiddenDangerMapper.queryDangerByCheckRecordId(id, null, null);
                    // 删除隐患信息
                    if (null != discoveryList && discoveryList.size() > 0) {
                        List<String> discoveryIdList = discoveryList.stream().map(bean -> bean.getId()).collect(Collectors.toList());
                        // 删除隐患整改通知书和隐患整改报告
                        // 获取隐患整改通知书数据
                        List<String> noticeId = rectificationMapper.getNoticeId(discoveryIdList);
                        if (null != noticeId && noticeId.size() > 0) {
                            // 删除隐患整改通知书详情
                            factory.getMapper(HiddenDangerRectificationMapper.class).batchDeleteNoticeItem(discoveryIdList);
                            // 删除隐患整改通知书
                            factory.getMapper(HiddenDangerRectificationMapper.class).batchDeleteNotice(noticeId);
                        }
                        // 获取隐患整改报告数据
                        List<String> reportId = rectificationMapper.getReportId(discoveryIdList);
                        if (null != reportId && reportId.size() > 0) {
                            // 删除隐患整报告详情
                            factory.getMapper(HiddenDangerRectificationMapper.class).batchDeleteReportItem(discoveryIdList);
                            // 删除隐患报告
                            factory.getMapper(HiddenDangerRectificationMapper.class).batchDeleteReport(reportId);
                        }
                        // 获取隐患整改流程信息
                        if (null != discoveryIdList && discoveryIdList.size() > 0) {
                            List<String> codeList = auditMapper.getAuditCodeByBusinessId(discoveryIdList);
                            if (null != codeList && codeList.size() > 0) {
                                auditMapper.batchDetele(codeList);
                            }
                        }
                        // 删除隐患信息
                        if (null != discoveryIdList && discoveryIdList.size() > 0) {
                            hiddenDangerMapper.batchDeleteDanger(discoveryIdList);
                            // 删除隐患整改信息
                            hiddenDangerMapper.bateDeleteRectificationByDiscoveryId(discoveryIdList);
                        }
                    }
                    // 删除检查明细数据
                    checklistEntryReferenceMapper.deleteBatchByCheckId(id);
                    // 删除检查记录流程
                    List<String> codeList = auditMapper.getAuditIdByBusinessId(id);
                    if (null != codeList && codeList.size() > 0) {
                        auditMapper.batchDetele(codeList);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    @Override
    public MessageBean<CheckRecord> queryOne(StaffBean user, String id) {
        MessageBean<CheckRecord> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            CheckRecord record = factory.getMapper(CheckRecordMapper.class).queryOne(id);
            getNames(record);
            CheckRecordDetail recordDetail = new CheckRecordDetail();
            Boolean authority = util.getAuthority(user);
            if (null != user && null != record) {
                if (record.getSubmit() == 0) {
                    record.setDeleteState(1);
                } else if (authority) {
                    record.setDeleteState(1);
                }
            }
            if (null != user && null != record && record.getWorkflowEditState() != 1) {
                // 判断当前登录用户是不是检查记录提交人或审批人
                if (record.getSubmitCode().equals(user.getCode()) || record.getIdentifier().split("_")[0].equals(user.getCode())) {
                    record.setWorkflowEditState(1);
                } else if (StringUtils.isNotEmpty(record.getNextParticipantCode()) && user.getUserid().equals(record.getNextParticipantCode())) {
                    record.setWorkflowEditState(1);
                }
            }
            Integer hiddenDangerDiscoveryCount = factory.getMapper(HiddenDangerMapper.class).countDangerByCheckRecordId(id);
            if (null != record.getAttachment() && !record.getAttachment().isEmpty()) {
                Integer attachmentCount = record.getAttachment().split(",").length;
                recordDetail.setAttachmentCount(attachmentCount);
            } else {
                recordDetail.setAttachmentCount(0);
            }
            recordDetail.setHiddenDangerDiscoveryCount(hiddenDangerDiscoveryCount);
            PropertyUtils.copyProperties(recordDetail, record);
            if (StringUtils.isNotEmpty(recordDetail.getDescription()) && recordDetail.getDescription().contains("null")) {
                recordDetail.setDescription(recordDetail.getDescription().replace("null", ""));
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询检查记录详情成功");
            msg.setData(recordDetail);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<CheckRecord>> queryByCondition(StaffBean user, String userCode, String planId, String corpCode, String gridCode, String manager, Integer planType, Integer submit, Integer start, Integer rows,String keyword) {
        MessageBean<DataBean<CheckRecord>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            String codes = util.getCodes(corpCode);
            List<CheckRecord> list = new ArrayList<>();
            // 获取所有记录
            List<CheckRecord> list1 = factory.getMapper(CheckRecordMapper.class).queryByCondition(planId, userCode, codes, gridCode, manager,
                    planType, submit, null, null,keyword);
//            rows = rows == null ? list.size() : (rows <= 0 ? 1 : rows);
            Integer count = 0;
            Boolean authority = util.getAuthority(user);
            if (null != list1 && list1.size() > 0) {
                for (CheckRecord record : list1) {
                    if (record.getSubmit() == 0) {
                        if (record.getSubmitCode().equals(user.getCode())) {
                            list.add(record);
                        } else {
                            count++;
                        }
                    } else {
                        list.add(record);
                    }
                }
            }
            Integer end = (start == 0 ? rows : start + rows);
            if (end > list.size()) {
                end = list.size();
                if (start > end) {
                    start = end;
                }
            }
            list.stream().forEach(bean -> {
                if (authority) {
                    bean.setDeleteState(1);
                } else if (bean.getSubmit() == 0) {
                    bean.setDeleteState(1);
                }
            });
            Integer totalNumber = factory.getMapper(CheckRecordMapper.class).countByCondition(planId, userCode, codes, gridCode, manager,
                    planType, submit,keyword);
            totalNumber = totalNumber - count;
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            //list.subList(start,end).forEach(item -> getNames(item));
            DataBean<CheckRecord> dataBean = new DataBean<>();
            dataBean.setList(list.subList(start, end));
            dataBean.setPageSize(rows);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询检查记录列表成功");
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<CheckRecord>> queryByPlanId(String planId, String corpCode, String gridCode, String manager, Integer planType, Integer submit, Integer start, Integer rows) {
        MessageBean<DataBean<CheckRecord>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<CheckRecord> list = factory.getMapper(CheckRecordMapper.class).queryByPlanId(planId, corpCode, gridCode, manager, planType, submit, start, rows);
            Integer totalNumber = factory.getMapper(CheckRecordMapper.class).countByPlanId(planId, corpCode, gridCode, manager, planType, submit);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            list.forEach(item -> getNames(item));
            DataBean<CheckRecord> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setPageSize(rows);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询检查记录列表成功");
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> saveAttachment(String id, MultipartFile[] files) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            if (null == files || files.length == 0) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CHANGE_FILE.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CHANGE_FILE.getDescription());
                return msg;
            }
            CheckRecord entity = factory.getMapper(CheckRecordMapper.class).queryOne(id);
            if (null == entity) {
                msg.setCode(BusinessCode.CHECKRECORD_NOT_EXISIT.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXISIT.getDescription());
                return msg;
            }
            if (entity.getSubmit() == 1 && entity.getWorkflowEditState() != 1) {
                msg.setCode(BusinessCode.CHECKRECORD_IS_COMMITED.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_IS_COMMITED.getDescription());
                return msg;
            }
            List<String> atts = new ArrayList<>();
            if (StringUtils.isNotEmpty(entity.getAttachment())) {
                atts = JSONObject.parseArray(entity.getAttachment(), String.class);
            }
            for (MultipartFile file : files) {
                String url = clientWrapper.uploadFile(file);
                atts.add(url + "#" + file.getOriginalFilename());
            }
            entity.setAttachment(new Gson().toJson(atts));
            Integer value = factory.getMapper(CheckRecordMapper.class).update(entity);
            if (value > 0) {
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("上传成功");
                return msg;
            } else {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("上传失败");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<List<CheckRecordAtrrBean>> fileList(String checkId) {
        MessageBean<List<CheckRecordAtrrBean>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<CheckRecordAtrrBean> list = new ArrayList<>();
            if (StringUtils.isEmpty(checkId)) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            CheckRecord checkRecord = factory.getMapper(CheckRecordMapper.class).queryOne(checkId);
            if (null == checkRecord) {
                msg.setCode(BusinessCode.CHECKRECORD_NOT_EXISIT.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXISIT.getDescription());
                return msg;
            }
            if (StringUtils.isNotEmpty(checkRecord.getAttachment())) {
                List<String> atts = JSONObject.parseArray(checkRecord.getAttachment(), String.class);
                for (String att : atts) {
                    String fileAddress = att.split("#")[0];
                    String fileName = att.split("#")[1];
                    CheckRecordAtrrBean bean = new CheckRecordAtrrBean();
                    bean.setFileAddress(fileAddress);
                    bean.setFileName(fileName);
                    list.add(bean);
                }
            } else {
                list = null;
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取附件列表成功");
            msg.setData(list);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> deleteFile(String id, String fileAddress, String fileName) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            CheckRecord checkRecord = factory.getMapper(CheckRecordMapper.class).queryOne(id);
            if (null == checkRecord) {
                msg.setCode(BusinessCode.CHECKRECORD_NOT_EXISIT.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXISIT.getDescription());
                return msg;
            }
            if (StringUtils.isNotEmpty(checkRecord.getAttachment())) {
                List<String> atts = JSONObject.parseArray(checkRecord.getAttachment(), String.class);
                String att = fileAddress + "#" + fileName;
                if (atts.contains(att)) {
                    //删除文件
                    atts.remove(att);
                    checkRecord.setAttachment(new Gson().toJson(atts));
                    Integer value = factory.getMapper(CheckRecordMapper.class).update(checkRecord);
                    if (value > 0) {
                        //删除指定附件
                        clientWrapper.deleteFile(fileAddress);
                        msg.setCode(BusinessCode.SUCCESS.getCode());
                        msg.setDescription("删除指定附件成功");
                        msg.setData(value);
                        factory.close();
                        return msg;
                    } else {
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription("删除指定附件失败");
                        msg.setData(value);
                        factory.close(false);
                        return msg;
                    }
                } else {
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("指定检查记录没有指定附件");
                    factory.close(false);
                    return msg;
                }
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("指定检查记录没有附件");
                msg.setData(-1);
                factory.close(false);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<CheckRecordReport> viewReport(String id) {
        MessageBean<CheckRecordReport> msg = new MessageBean<>();
        CheckRecordReport recordReport = new CheckRecordReport();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            CheckRecord checkRecord = queryOne(null, id).getData();
            if (null == checkRecord) {
                msg.setCode(BusinessCode.CHECKRECORD_NOT_EXISIT.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXISIT.getDescription());
                return msg;
            }
            recordReport.setCheckManager(checkRecord.getManagerName());
            StringBuilder checkPerson = new StringBuilder();
            checkPerson.append(checkRecord.getManagerName().split("_")[0]).append(",");
            if (StringUtils.isNotEmpty(checkRecord.getInnerWorkersName())) {
                List<String> innerWorkersList = Arrays.asList(checkRecord.getInnerWorkersName().split(","));
                for (String innerWorkers : innerWorkersList) {
                    String name = innerWorkers.split("_")[0];
                    checkPerson.append(name).append(",");
                }
            }
            if (StringUtils.isNotEmpty(checkRecord.getOutterWorkers())) {
                String[] outterWorkersList = checkRecord.getOutterWorkers().split("[,，]");
                for (String outterWorkers : outterWorkersList) {
                    String name = outterWorkers.split("_")[0];
                    checkPerson.append(name).append(",");
                }
            }
            recordReport.setCheckPerson(checkPerson.toString().substring(0, checkPerson.lastIndexOf(",")));
            recordReport.setCheckTime(checkRecord.getCheckTime());
            recordReport.setCorpName(checkRecord.getCorpName());
            recordReport.setGridName(checkRecord.getGridName());
            recordReport.setSafetyCheckCode(checkRecord.getCode());
            recordReport.setSafetyCheckName(checkRecord.getName());
            recordReport.setManagerDepartmentName(checkRecord.getManagerName().split("_")[1]);
            recordReport.setDescription(checkRecord.getDescription());
            recordReport.setInspectorsSign(checkRecord.getInspectorsSign());
            recordReport.setInspectedUnitLeadSign(checkRecord.getInspectedUnitLeadSign());
            //查询该次检查记录使用的检查表和检查项信息
            List<ChecklistEntryReference> referenceList = factory.getMapper(ChecklistEntryReferenceMapper.class).queryByCheckRecordId(id, null, null);
            if (null != referenceList && referenceList.size() > 0) {
                referenceList.forEach(item -> referenceService.getNames(item));
                recordReport.setReferenceAndItemsList(referenceList);
            }
            //查询本次检查记录的隐患列表
            List<HiddenDangerDiscovery> dangerDiscoveries = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(id, null, null);
            if (dangerDiscoveries != null && dangerDiscoveries.size() > 0) {
                dangerDiscoveries.forEach(item -> {
                    dangerDiscoveryService.getNames(item);
                    if (StringUtils.isEmpty(item.getSolution())) {
                        item.setSolution(item.getHandlingOpinions());
                    }
                });
                recordReport.setDangerDiscoveryList(dangerDiscoveries);
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            msg.setData(recordReport);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<CheckRecord>> indexCheckRecordList(String code, Integer start, Integer rows) {
        MessageBean<DataBean<CheckRecord>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            String simpleCode = code.split("_")[0];
            List<CheckRecord> list = factory.getMapper(CheckRecordMapper.class).indexCheckRecordList(code, simpleCode, start, rows);
            Integer totalNumber = factory.getMapper(CheckRecordMapper.class).countIndexCheckRecordList(code, simpleCode);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            list.forEach(item -> getNames(item));
            DataBean<CheckRecord> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setPageSize(rows);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询检查记录列表成功");
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public XSSFWorkbook exportReport(String id, InputStream inputStream) {
        // 获取检查记录数据
        MessageBean<CheckRecordReport> msg = viewReport(id);
        CheckRecordReport report = null;
        if (msg.getCode() == BusinessCode.SUCCESS.getCode()) {
            if (null != msg.getData()) {
                report = msg.getData();
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(inputStream);
            // 导出检查记录数据
            if (null != report) {
                CellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                cellStyle.setWrapText(true);
                XSSFSheet sheet = workbook.getSheetAt(0);
                // 设置检查记录内容
                XSSFRow row;
                row = sheet.getRow(0);
                row.getCell(0).setCellValue(report.getSafetyCheckName());
                row.setRowStyle(cellStyle);
                row = sheet.getRow(1);
                row.getCell(6).setCellValue(report.getSafetyCheckCode());
                row.setRowStyle(cellStyle);
                row = sheet.getRow(2);
                row.getCell(2).setCellValue(report.getManagerDepartmentName());
                row.getCell(6).setCellValue(report.getCheckPerson());
                row.setRowStyle(cellStyle);
                row = sheet.getRow(3);
                row.getCell(2).setCellValue(report.getGridName());
                row.getCell(6).setCellValue(format.format(report.getCheckTime()));
                row.setRowStyle(cellStyle);
                row = sheet.getRow(4);
                row.getCell(2).setCellValue(report.getDescription());
                row.setRowStyle(cellStyle);
                int rowNum = 6;
                // 设置检查明细数据
                List<ChecklistEntryReference> references = report.getReferenceAndItemsList();
                if (null != references && references.size() > 0) {
                    int index = 1;
                    for (ChecklistEntryReference reference : references) {
                        row = sheet.getRow(rowNum);
                        row.createCell(0).setCellValue(index);
                        row.createCell(1).setCellValue(reference.getChecklistEntryName());
                        // 合并单元格
                        // 指定 4 个参数，起始行，结束行，起始列，结束列。然后这个区域将被合并
                        CellRangeAddress region = new CellRangeAddress(rowNum, rowNum, 1, 7);
                        sheet.addMergedRegion(region);
                        index++;
                        rowNum++;
                    }
                }
                // 设置隐患记录数据
                row = sheet.getRow(rowNum);
                row.createCell(0).setCellValue("二");
                row.createCell(1).setCellValue("隐患记录");
                CellRangeAddress region = new CellRangeAddress(rowNum, rowNum, 1, 7);
                sheet.addMergedRegion(region);
                rowNum++;
                // 设置隐患表头
                row = sheet.getRow(rowNum);
                row.createCell(0).setCellValue("被检查单位");
                row.createCell(1).setCellValue("检查情况");
                row.createCell(2).setCellValue("隐患分类");
                row.createCell(3).setCellValue("整改意见");
                row.createCell(4).setCellValue("整改人");
                row.createCell(5).setCellValue("整改结果");
                row.createCell(6).setCellValue("复核人");
                row.createCell(7).setCellValue("复核时间");
                rowNum++;
                List<HiddenDangerDiscovery> dangerDiscoveryList = report.getDangerDiscoveryList();
                if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                    for (HiddenDangerDiscovery discovery : dangerDiscoveryList) {
                        row = sheet.getRow(rowNum);
                        row.createCell(0).setCellValue(discovery.getGridName());
                        // 设置单元格自动换行
                        row.getCell(0).getCellStyle().setWrapText(true);
                        row.createCell(1).setCellValue(discovery.getDescription());
                        row.getCell(1).getCellStyle().setWrapText(true);
                        row.createCell(2).setCellValue(discovery.getDangerTypeName());
                        row.getCell(2).getCellStyle().setWrapText(true);
                        row.createCell(3).setCellValue(discovery.getSolution());
                        row.getCell(3).getCellStyle().setWrapText(true);
                        row.createCell(4).setCellValue(discovery.getRectifierName());
                        row.getCell(4).getCellStyle().setWrapText(true);
                        row.createCell(5).setCellValue(discovery.getRectificationResult());
                        row.getCell(5).getCellStyle().setWrapText(true);
                        row.createCell(6).setCellValue(discovery.getReviewerName());
                        row.getCell(6).getCellStyle().setWrapText(true);
                        String reviewTimeStr = null;
                        Date reviewTime = discovery.getReviewTime();
                        if (null != reviewTime) {
                            reviewTimeStr = format.format(reviewTime);
                        }
                        row.createCell(7).setCellValue(null == reviewTimeStr ? reviewTimeStr : "");
                        row.getCell(7).getCellStyle().setWrapText(true);
                        // 设置行高
                        row.setHeightInPoints(30);
                        rowNum++;
                    }
                }
                row = sheet.getRow(rowNum);
                region = new CellRangeAddress(rowNum, rowNum, 0, 1);
                sheet.addMergedRegion(region);
                row.createCell(0).setCellValue("检查人员签名(默认第一个)");
                row.getCell(0).getCellStyle().setAlignment(HSSFCellStyle.ALIGN_CENTER);
                // 获取检查人员签字图片
                String inspectorsSign = report.getInspectorsSign();
                XSSFDrawing drawing = sheet.createDrawingPatriarch();
                if (StringUtils.isNotEmpty(inspectorsSign)) {
                    List<String> list = JSONArray.parseArray(inspectorsSign, String.class);
                    String url = null;
                    if (null != list && list.size() > 0) {
                        // 如果有多张图片，则取第一张
                        url = list.get(0).split("#")[0];
                    }
                    if (null != url) {
                        // 对图片单独捕获异常
                        try {
                            URL imgUrl = new URL(url);
                            String suffix = url.substring(url.lastIndexOf(".") + 1);
                            BufferedImage bufferImg = ImageIO.read(imgUrl);
                            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                            ImageIO.write(bufferImg, suffix, byteArrayOut);
                            XSSFClientAnchor anchor = new XSSFClientAnchor(1, 1, 1, 1, 2, rowNum, 4, rowNum + 1);
                            //插入图片
                            drawing.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
                        } catch (Exception e) {
                            logger.error(e.getMessage(),e);
                        }
                    }
                }
                region = new CellRangeAddress(rowNum, rowNum, 2, 3);
                sheet.addMergedRegion(region);
                region = new CellRangeAddress(rowNum, rowNum, 4, 5);
                sheet.addMergedRegion(region);
                region = new CellRangeAddress(rowNum, rowNum, 6, 7);
                sheet.addMergedRegion(region);
                row.createCell(4).setCellValue("受检单位负责人签名(默认第一个)");
                row.getCell(4).getCellStyle().setAlignment(HSSFCellStyle.ALIGN_CENTER);
                // 获取受检单位负责人签字图片
                String inspectedUnitLeadSign = report.getInspectedUnitLeadSign();
                if (StringUtils.isNotEmpty(inspectedUnitLeadSign)) {
                    List<String> list = JSONArray.parseArray(inspectedUnitLeadSign, String.class);
                    String url = null;
                    if (null != list && list.size() > 0) {
                        // 如果有多张图片，则取第一张
                        url = list.get(0).split("#")[0];
                    }
                    if (null != url) {
                        // 对图片单独捕获异常
                        try {
                            URL imgUrl = new URL(url);
                            String suffix = url.substring(url.lastIndexOf(".") + 1);
                            BufferedImage bufferImg = ImageIO.read(imgUrl);
                            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                            ImageIO.write(bufferImg, suffix, byteArrayOut);
                            XSSFClientAnchor anchor = new XSSFClientAnchor(1, 1, 1, 1, 6, rowNum, 8, rowNum + 1);
                            //插入图片
                            drawing.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
                        } catch (Exception e) {
                            logger.error(e.getMessage(),e);
                        }
                    }
                }
                row.setHeightInPoints(50);
            }
            return workbook;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public List<CheckRecord> exportList(StaffBean user, String corpCode, String userCode, String planId, String gridCode, String manager, Integer planType, Integer submit) {
        try (SessionFactory factory = new SessionFactory()) {
            String codes = util.getCodes(corpCode);
            List<CheckRecord> list = new ArrayList<>();
            // 获取所有记录
            List<CheckRecord> list1 = factory.getMapper(CheckRecordMapper.class).queryByCondition(planId, userCode, codes, gridCode, manager,
                    planType, submit, null, null,null);
            if (null != list1 && list1.size() > 0) {
                for (CheckRecord record : list1) {
                    if (record.getSubmit() == 0) {
                        if (record.getSubmitCode().equals(user.getCode())) {
                            list.add(record);
                        }
                    } else {
                        list.add(record);
                    }
                }
            }
            if (null != list && list.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                list.forEach(bean -> {
                    if (null != bean.getCheckTime()) {
                        bean.setCheckTimeStr(sdf.format(bean.getCheckTime()));
                    }
                    if (null != bean.getSubmitTime()) {
                        bean.setSubmitTimeStr(sdf1.format(bean.getSubmitTime()));
                    }
                    PerformancePlan plan = factory.getMapper(PerformancePlanMapper.class).queryOne(bean.getPlanId());
                    if (null != plan) {
                        bean.setPlanName(plan.getName());
                    } else {
                        bean.setPlanName("不在计划内");
                    }
                });
            }
            factory.close();
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public MessageBean<DataBean<CheckRecord>> homePageCheckList(StaffBean user, String userCode, String planId, String corpCode, String gridCode, String manager, Integer planType, Integer submit, Integer start, Integer rows) {
        MessageBean<DataBean<CheckRecord>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<CheckRecord> list = factory.getMapper(CheckRecordMapper.class).homePageCheckList(planId, corpCode, gridCode, manager, planType, submit, start, rows);
            Integer totalNumber = factory.getMapper(CheckRecordMapper.class).homePageCheckCount(planId, corpCode, gridCode, manager, planType, submit);
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<CheckRecord> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setPageSize(rows);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询首页安全检查成功");
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }

    }

    private String generateCaode(SessionFactory factory, String cropCode) {
        String date = format.format(new Date());
        StringBuilder code = new StringBuilder("C");
        code = code.append(date.substring(2, 4));
        Integer count = factory.getMapper(CheckRecordMapper.class).count(code.toString());
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        nf.setMaximumIntegerDigits(4); // 设置最大整数位数
        nf.setMinimumIntegerDigits(4); // 设置最小整数位数
        code.append(nf.format(count));
        return code.toString();
    }

    private void getNames(CheckRecord bean) {
        if (null != bean) {
            SessionFactory factory = new SessionFactory();
            if (StringUtils.isNotEmpty(bean.getCorpCode())) {
                CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(bean.getCorpCode());
                bean.setCorpName(corpBean == null ? null : corpBean.getCorpName());
            }
            factory.close();
            if (StringUtils.isNotEmpty(bean.getInnerWorkers())) {
                bean.setInnerWorkers(JSONArray.parseArray(bean.getInnerWorkers(), String.class).stream().collect(Collectors.joining(",")));
            }
            if (StringUtils.isNotEmpty(bean.getInnerWorkersName())) {
                bean.setInnerWorkersName(JSONArray.parseArray(bean.getInnerWorkersName(), String.class).stream().collect(Collectors.joining(",")));
            }
            if (StringUtils.isNotEmpty(bean.getInspectedUnitLead())) {
                bean.setInspectedUnitLead(JSONArray.parseArray(bean.getInspectedUnitLead(), String.class).stream().collect(Collectors.joining(",")));
            }
            if (StringUtils.isNotEmpty(bean.getInspectedUnitLeadName())) {
                bean.setInspectedUnitLeadName(JSONArray.parseArray(bean.getInspectedUnitLeadName(), String.class).stream().collect(Collectors.joining(",")));
            }
        }
    }

    public Port getPort() {
        SecretBean bean = new SecretBean();
        bean.setSecret(secret);
        bean.setAppid(appid);
        return new Port(bean);
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            CheckRecord record = factory.getMapper(CheckRecordMapper.class).queryOne(audit.getBusinessIds());
            if (null != record) {
                record.setSubmit(2);
                //修改流程中编辑状态为不可修改
                record.setWorkflowEditState(0);
                factory.getMapper(CheckRecordMapper.class).update(record);
                //根据检查记录id去查找是否有任务的存在
                JobsTasks jobsTasks = factory.getMapper(JobsTasksMapper.class).queryJobsTasksByBusinId(record.getId());
                if (null != jobsTasks) {
                    jobsTasks.setState(1);
                    factory.getMapper(JobsTasksMapper.class).completed(jobsTasks);
                }
                // 获取检查记录下的隐患记录
                List<HiddenDangerDiscovery> dangerDiscoveryList = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(audit.getBusinessIds(),
                        null, null);
                // 检查记录审批完成后，自动启动隐患整改流程
                if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                    // 获取检查记录提交人
                    String submitCode = record.getSubmitCode();
                    List<StaffBean> submitStaffBeanList = (List<StaffBean>) util.staff(submitCode.split("_")[0], null).getData();
                    StaffBean user = submitStaffBeanList.get(0);
                    // 获取隐患负责人
                    Set<String> codeLists = dangerDiscoveryList.stream().map(bean -> bean.getDangerManager().split("_")[0]).collect(Collectors.toSet());
                    List<String> noticeCodeList = new ArrayList<>();
                    for (String code : codeLists) {
                        try (SessionFactory sessionFactory = new SessionFactory()) {
                            // 同一个隐患负责人，提交成一条隐患流程
                            List<HiddenDangerDiscovery> discoveryList = dangerDiscoveryList.stream().filter(bean -> code.equals(bean.getDangerManager().split("_")[0])).collect(Collectors.toList());
                            //整理隐患整改记录
                            HiddenDangerMapper mapper = sessionFactory.getMapper(HiddenDangerMapper.class);
                            List<HiddenDangerRectification> rectificationList = new ArrayList<>();
                            List<HiddenDangerRectification> deleteList = new ArrayList<>();
                            List<String> approvalList = new ArrayList<>();
                            for (HiddenDangerDiscovery dangerDiscovery : discoveryList) {
                                //查询提交的隐患是不是已经有了整改记录；
                                List<HiddenDangerRectification> rectificationList1 = sessionFactory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(dangerDiscovery.getId());
                                //删除之前有的整改记录信息
                                if (rectificationList1 != null && rectificationList1.size() > 0) {
                                    deleteList.addAll(rectificationList1);
                                }
                                //保存隐患整改信息，主要是配置隐患整改信息的验证人
                                HiddenDangerRectification rectification = new HiddenDangerRectification();
                                //保存整改信息
                                rectification.setHiddenDangerId(dangerDiscovery.getId());
                                rectification.setId(DefaultIdGenerator.getInstance().generateLongId());
                                rectification.setAddTime(dangerDiscovery.getUpdateTime());
                                rectification.setAddUser(user.getName());
                                rectification.setUpdateTime(dangerDiscovery.getUpdateTime());
                                rectification.setUpdateUser(user.getName());
                                rectification.setRectifier(dangerDiscovery.getDangerManager());
                                rectification.setRectifierName(dangerDiscovery.getDangerManagerName());
                                rectification.setDeadline(dangerDiscovery.getRectificationPeriod());
                                rectification.setSolution(dangerDiscovery.getHandlingOpinions());
                                List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(dangerDiscovery.getDangerManager().split("_")[0], null).getData();
                                List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(dangerDiscovery.getDangerManager().split("_")[0]).getData();
                                if (!approvalList.contains(staffBeanList.get(0).getUserid())) {
                                    approvalList.add(staffBeanList.get(0).getUserid());
                                }
                                rectification.setReviewer(dangerDiscovery.getDangerManager().split("_")[0]);
                                rectification.setReviewerName(staffBeanList.get(0).getName() + "_" + deptBeanList.get(0).getName());
                                rectification.setDelayState(0);
                                IndicationItems items = sessionFactory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "未整改");
                                rectification.setRectificationState(items == null ? null : items.getId());
                                rectificationList.add(rectification);
                            }
                            //更新选中的隐患为确认状态；启动隐患流程
                            List<String> ids = discoveryList.stream().map(bean -> bean.getId()).collect(Collectors.toList());
                            mapper.updateDangerState(2, ids);
                            try {
                                for (HiddenDangerDiscovery discovery : discoveryList) {
                                    List<Message> messages = new ArrayList<>();
                                    if (discovery.getCopyPerson() != null) {
                                        String[] copyPersons = discovery.getCopyPerson().split(",");
                                        for (String copyPerson : copyPersons) {
                                            Message message = new Message();
                                            message.setId(DefaultIdGenerator.getInstance().generateLongId());
                                            message.setTitle("有一项您关注的隐患整改");
                                            message.setIsRead(0);
                                            message.setIsRemove(0);
                                            message.setAddTime(new Date());
                                            message.setAddUser(discovery.getAddUser());
                                            message.setContent("隐患描述：" + discovery.getDescription());
                                            message.setReceiverCode(copyPerson.split("_")[0]);
                                            messages.add(message);
                                        }
                                    }
                                    if (messages != null && messages.size() > 0) {
                                        factory.getMapper(MessageMapper.class).batchInsert(messages);
                                    }
                                }
                            } catch (Exception e) {
                                logger.error(e.getMessage(),e);
                            }
                            mapper.batchInsertRectification(rectificationList);
                            if (deleteList != null && deleteList.size() > 0) {
                                List<String> deleteIdList = deleteList.stream().map(HiddenDangerRectification::getId).collect(Collectors.toList());
                                mapper.bateDeleteRectification(deleteIdList);
                            }
                            Date date = new Date();
                            Audit auditBean = new Audit();
                            auditBean.setId(DefaultIdGenerator.getInstance().generateLongId());
                            auditBean.setUpdateUser(user.getName());
                            auditBean.setUpdateTime(date);
                            auditBean.setAddTime(date);
                            auditBean.setAddUser(user.getName());
                            auditBean.setFlowType(2);
                            auditBean.setOperation(1);
                            auditBean.setTarget(HiddenDangerDiscoveryServiceImpl.class.getName());
                            auditBean.setFlowName(Immutable.HIDDENDANGER_WORKFLOW);
                            auditBean.setNowNodeCode("Process-task2");
                            auditBean.setTitle("隐患整改流程");
                            auditBean.setCorpCode(discoveryList.get(0).getCorpCode());
                            auditBean.setBusinessIds(new Gson().toJson(ids));
                            auditBean.setInitiatorCode(user.getCode());
                            auditBean.setTemplateKey(hiddenDangerWorkFlow);
                            auditBean.setInitiatorAccount(user.getUserid());
                            auditBean.setSetCode(riskDangerSetCode);
                            auditBean.setDescription("隐患整改流程");
                            auditBean.setState(1);
                            Map<String, Object> businessDataMap = new HashMap<>();
                            String userid = approvalList.stream().collect(Collectors.joining(","));
                            businessDataMap.put("rectifier", userid);
                            businessDataMap.put("reviewer", userid);
                            businessDataMap.put("verification", user.getUserid());
                            if (!flowManagement.initFlow(user, auditBean, businessDataMap)) {
                                // 如果自动提交隐患失败，将隐患修改为草稿，可在隐患台账处提交
                                factory.getMapper(HiddenDangerMapper.class).updateDangerState(0, ids);
                                sessionFactory.close(false);
                            } else {
                                // 提交成功，生成整改通知书
                                String noticeCode = HiddenDangerRectificationServiceImpl.generateHiddenDangerRectificationNotice(sessionFactory, user, discoveryList);
                                if (StringUtils.isNotEmpty(noticeCode)) {
                                    noticeCodeList.add(noticeCode);
                                }
                                sessionFactory.close();
                            }
                        }
                    }
                    if (null != noticeCodeList && noticeCodeList.size() > 0) {
                        String noticeCodes = noticeCodeList.stream().collect(Collectors.joining(","));
                        factory.getMapper(CheckRecordMapper.class).updateCheckNoticeCode(noticeCodes, record.getId());
                    }
                }
                /*
                //由于无法自动启动流程无法知道是由谁确认整改人等信息，所以直接将检查记录的状态修改成会签结束,并修改隐患的状态为草稿状态即可，用户
                //可以在隐患台账列表那里自动启动隐患流程
                //将检查中的隐患状态修改成草稿状态，使得可以在隐患台账处提交
                if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                    for (HiddenDangerDiscovery dangerDiscovery : dangerDiscoveryList) {
                        dangerDiscovery.setState(0);
                    }
                    factory.getMapper(HiddenDangerMapper.class).batchUpdateDanger(dangerDiscoveryList);
                }*/
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
        } finally {
            factory.close();
        }
    }

    @Override
    public void discardApproval(Audit audit) {

    }

    @Override
    public void processDiscard(Audit audit) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            CheckRecord entity = factory.getMapper(CheckRecordMapper.class).queryOne(audit.getBusinessIds());
            if (null != entity) {
                entity.setSubmit(0);
                //修改流程中编辑状态为不可修改
                entity.setWorkflowEditState(0);
                factory.getMapper(CheckRecordMapper.class).update(entity);
            }
            factory.close();
        } catch (Exception e) {
            if (null != factory) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(CheckRecordServiceImpl.class.getName(), this);
        //map.put(HiddenDangerDiscoveryServiceImpl.class.getName(), new HiddenDangerDiscoveryServiceImpl());
    }

    /**
     * 流程驳回操作
     *
     * @param audit
     * @param userIdList 节点审批人
     */
    @Override
    public void reject(Audit audit, List<String> userIdList) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            CheckRecord entity = factory.getMapper(CheckRecordMapper.class).queryOne(audit.getBusinessIds());
            if (null != entity) {
                //修改流程中编辑状态为可修改
                factory.getMapper(CheckRecordMapper.class).updateWorkflowEditState(entity.getId(), 1);
            }
            factory.close();
        } catch (Exception e) {
            if (null != factory) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 流程提交成功操作
     *
     * @param operation
     * @param audit
     */
    @Override
    public void passApproval(Integer operation, Audit audit) {
        try (SessionFactory factory = new SessionFactory()) {
            if (operation == 32) {
                CheckRecord entity = factory.getMapper(CheckRecordMapper.class).queryOne(audit.getBusinessIds());
                if (null != entity && entity.getWorkflowEditState() == 1) {
                    //修改流程中编辑状态为不可修改
                    factory.getMapper(CheckRecordMapper.class).updateWorkflowEditState(entity.getId(), 0);
                }
            } else if (operation == 2) {
                // 转办
                CheckRecord entity = factory.getMapper(CheckRecordMapper.class).queryOne(audit.getBusinessIds());
                if (null != entity) {
                    //修改流程中编辑状态为不可修改
                    factory.getMapper(CheckRecordMapper.class).updateNextParticipantCode(entity.getId(), audit.getNextParticipantCode());
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }
}
